package com.sast.manage_backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sast.manage_backend.model.TempHumid;
import com.sast.manage_backend.service.TempHumidService;
import com.sast.manage_backend.mapper.TempHumidMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author 86139
* @description 针对表【temp_humid】的数据库操作Service实现
* @createDate 2025-08-13 08:28:33
*/
@Service
public class TempHumidServiceImpl extends ServiceImpl<TempHumidMapper, TempHumid>
    implements TempHumidService{


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public TempHumid getTempHumidByDeviceId(short id) {
        // 1.先取redis数据库中的
        String temp = stringRedisTemplate.opsForValue().get("temp_" + id);
        String humid = stringRedisTemplate.opsForValue().get("humid_" + id);

        if(temp != null && humid != null) {
            TempHumid tempHumid = new TempHumid();
            tempHumid.setDeviceId((int) id);
            tempHumid.setTemperature(Double.parseDouble(temp));
            tempHumid.setHumidity(Double.parseDouble(humid));
            tempHumid.setDatetime(new Date());
            return tempHumid;
        }
        // 2.如果redis中没有，则从数据库中取
        else {
            LambdaQueryWrapper<TempHumid> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TempHumid::getDeviceId,id);
            wrapper.orderByDesc(TempHumid::getDatetime);
            wrapper.last("LIMIT 1");
            return this.getOne(wrapper,false);
        }

    }
}




